const cartModel = require('../db/cart')
const respond = require('../utils/respond')
module.exports = {
    addcart: async (req, res) => {
        let { price, currentPrice, userid, goodsid, goodsnumber,title,imgBigLogo,imgSmallLogo} = req.body
        // 存储到数据库
        // 判断数据库中是否有这个用户的这个商品
        let cartData = await cartModel.findOne({userid, goodsid})
        if(cartData) {
            await cartModel.updateOne({userid, goodsid}, {goodsnumber: cartData.goodsnumber+1})
            respond(res, 0, '添加成功')
        }  else {
            let docs = await cartModel.insertMany([{
                price,
                currentPrice,
                imgBigLogo,
                imgSmallLogo,
                title,
                userid,
                goodsid,
                goodsnumber
            }])
            if(docs.length === 0) {
                respond(res, 1, '添加失败')
                return
            }
            respond(res, 0, '添加成功')
        }
        
    },
    getCartAllGoods: async (req, res) => {
        // 获取get请求的参数
        let {page, size} = req.params
        // 判断当前页不能为空
        if(!page) {
            respond(res, 1, '缺少当前页参数')
            return
        }
        // 根据page当前页获取当前页的数据
        let docs = await cartModel.find({}, {__v: 0}, {skip: (page-1)*size, limit: size})
        if(!docs.length) {
            respond(res, 2, '获取商品数据失败')
            return
        }
        let total = await cartModel.count()
        let totalPage = Math.ceil(total / size)
        // console.log(totalPage);
        respond(res, 0, '获取商品数据成功', {
            data: docs,
            totalPage
        })
    },
    
}